/**
 * 子进程
 * 存储数据
 **/

const cp = require('child_process');
const { resolve } = require('path');

(async () => {
    // 要运行的脚本
    const script = resolve(__dirname, './movie_list/movie_list');
    // 进程池
    const cd = cp.fork(script, []);
    let invoked = false;

    cd.on('error', err => {
        if(invoked) {
            return
        }
        invoked = true;
        console.log(err)

    });

    cd.on('exit', code => {
        if (invoked) {
            return
        }
        invoked = false;
        let err = 0 === code ? null : new Error('exit code' + code);
        console.log(err)
    });
    // 子进程接收数据
    cd.on('message', data => {
        let result = data.result;

        const mysql = require('mysql');
        //  创建连接
        const connection = mysql.createConnection({
        host : 'localhost',
        port : '8889',
        user : 'root',
        password : 'root',
        database : 'movie_douban'
        });
        //  执行创建连接
        connection.connect();

        // 构造要写入的数据
        const insertData = [];

        for (let i = 0; i < result.length; i++) {
            const el = result[i];
            const _data = [el.rate, el.title, el.url];
            insertData.push(_data);
        }

        // 插入多条数据
        const sql = "INSERT INTO movie_list (`rate`, `title`, `url`) VALUES ?";

        connection.query(sql, [insertData], (err, res) => {
           if (err) {
               console.log(err);
           } else {
               console.log('INSERT SUCCESS')
           }
        });
        // 断开
        connection.end();
        // 执行完结束进程
        // process.exit(0);
    })
})();